package servlet;

import util.ParameterUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author 石小俊
 * 用于实现添加员工的功能
 */
@WebServlet("/addEmp")
public class AddEmpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 指定post请求字符集
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
//        out.println("<h1>即将执行添加员工的功能</h1>");

        // 获取表单数据
        // 在请求对象HttpServletRequest中,提供了获取表单数据的方法
        // 一般使用两种方法
        // 1.String value getParameter(String key):根据表单数据的key获取对应的value,返回值是字符串类型
        // 2.String[] arr = getParameterValues(String key):根据表单数据的key获取对应的value,返回值是字符串数组
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // JDBC操作
            // 1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            // 3.获取状态集
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp(name,salary,gender,edu,hobbies)")
                    .append(" values(?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            // 设置参数
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, ParameterUtil.arrayToString(hobbies));

            // 4.执行sql
            ps.executeUpdate();

            // 5.结果集映射,仅限查询操作

            // 成功后返回响应
            // out.println("<h1 style='color:green;'>恭喜您,添加成功</h1>");

            // 重定向
            resp.sendRedirect("findAll");
//            resp.sendRedirect("https://www.baidu.com/");
//            resp.sendRedirect("/WEB-INF/test.jsp");

            // 转发
//            req.getRequestDispatcher("findAll").forward(req,resp);
//            req.getRequestDispatcher("https://www.baidu.com/").forward(req,resp);
//            req.getRequestDispatcher("/WEB-INF/test.jsp").forward(req,resp);
        } catch (Exception e) {
            // 失败后返回响应
            out.println("<h1 style='color:red;'>对不起,添加失败,失败原因:" + e.getMessage() + "</h1>");
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    out.println("<h1 style='color:red;'>释放连接失败,失败原因:" + e.getMessage() + "</h1>");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    out.println("<h1 style='color:red;'>释放状态集失败,失败原因:" + e.getMessage() + "</h1>");
                }
            }
        }
    }
}
